//
//  GJDBViewController_Detail.m
//  Estate
//
//  Created by heyong on 16/6/24.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "SegmentViewController.h"
#import "GLDBViewController_Detail_B.h"
#import "ProcessRecordModel.h"
#import "JLLiuZhuanViewController.h"
#import "FDAlertView.h"
#import "AlertVIew.h"
#import "BasicInformationViewController.h"

#import "GJDBViewController_Detail.h"


@interface GJDBViewController_Detail ()
{
    FDAlertView *alert;
    //判断是否合格
    int _qualified;
}

// 说明
@property (copy, nonatomic)NSString *content;
// 流程记录ID
@property (strong, nonatomic) NSString *flowRecordID;
// 附件信息
@property (strong, nonatomic) NSString *fileinfos;
/**流程数据数组 */
@property (nonatomic,strong) NSMutableArray *processRecoedArray;
// 最新的流程记录
@property (nonatomic,strong) ProcessRecordModel *currentRecordModel;
@end


@implementation GJDBViewController_Detail

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    // 获取数据
    if (self.processId) {
        self.processRecoedArray = [self getProgessRecordModelArrayWithID:self.processId];
        self.currentRecordModel = [self.processRecoedArray firstObject];
        
    }
    if(!self.currentRecordModel) {
        [LSUtility showToastWithMessage:@"数据获取异常。" inView:self.view Andtime:1.8];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }
    // 流程类型
    if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE) {
        self.title = @"督办单";
        
    } else if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW) {
        self.title = @"跟进单";
    }
    // 监理督办, 发送形式为无
    if (self.JLDuB) {
        if  (self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK || self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW_PASS_NO) {    // 其他发送形式且状态为待复查
            [self createView];
            self.isEdit = YES;
        }
    }
    [self createsliderBtn];
}

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reView:) name:@"succeedJLDuBan" object:nil];
}
//获取流程记录
- (NSMutableArray *)getProgessRecordModelArrayWithID:(NSString *)ID{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME), date(CREATE_TIME) FROM PROCESS_RECORD WHERE PROCESS_ID = '%@' ORDER BY CREATE_TIME DESC", ID];
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *processRecordArray = [NSMutableArray array];
    
    while ([result next]) {
        ProcessRecordModel *prModel = [[ProcessRecordModel alloc] init];
        prModel.ID= [result stringForColumn:@"ID"];
        prModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        prModel.PROCESS_ID = [result stringForColumn:@"PROCESS_ID"];
        prModel.ADDRESS_ID = [result stringForColumn:@"ADDRESS_ID"];
        prModel.ADDRES_INFO = [result stringForColumn:@"ADDRES_INFO"];
        prModel.PROCESS_TYPE = [result intForColumn:@"PROCESS_TYPE"];
        prModel.PROCESS_STAGE = [result intForColumn:@"PROCESS_STAGE"];
        prModel.RECORD_USER = [result stringForColumn:@"RECORD_USER"];
        prModel.PROBLEM_TYPE = [result intForColumn:@"PROBLEM_TYPE"];
        prModel.RECORD_MASTER = [result stringForColumn:@"RECORD_MASTER"];
        prModel.RECIFY_USER = [result stringForColumn:@"RECIFY_USER"];
        prModel.RECIFY_UNIT = [result stringForColumn:@"RECIFY_UNIT"];
        prModel.SEVERITY = [result stringForColumn:@"SEVERITY"];
        prModel.END_TIME = [result stringForColumn:@"END_TIME"];
        prModel.SEND_TIME = [result stringForColumn:@"SEND_TIME"];
        prModel.SEND_TYPE = [result intForColumn:@"SEND_TYPE"];
        prModel.PROCESS_TITLE = [result stringForColumn:@"PROCESS_TITLE"];
        prModel.PROCESS_CONTENT = [result stringForColumn:@"PROCESS_CONTENT"];
        prModel.PROCESS_REQUIRED = [result stringForColumn:@"PROCESS_REQUIRED"];
        prModel.PROCESS_DESC = [result stringForColumn:@"PROCESS_DESC"];
        prModel.SUBMITTORS = [result stringForColumn:@"SUBMITTORS"];
        prModel.PUT_USER = [result stringForColumn:@"PUT_USER"];
        prModel.REVIEW_OPINION = [result stringForColumn:@"REVIEW_OPINION"];
        prModel.FILEINFOS = [result stringForColumn:@"FILEINFOS"];
        prModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        prModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        prModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        prModel.CREATE_DATE = [result stringForColumn:@"date(CREATE_TIME)"];
        prModel.SUBCREATE_TIME = [result stringForColumn:@"time(CREATE_TIME)"];
        prModel.zhuangtai = [result intForColumn:@"REVIEW_STATE"];
        prModel.REVIEW_USER = [result stringForColumn:@"REVIEW_USER"];
        //本地状态 用于判断能否编辑
        prModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        [processRecordArray addObject:prModel];
    }
    [db close];
    return processRecordArray;
}
- (void)createsliderBtn {
    SegmentViewController *vc = [[SegmentViewController alloc]init];
    vc.height = DEF_SCREEN_HEIGHT - 108;
    NSMutableArray *controlArray = [[NSMutableArray alloc] init];
    
    // 基本信息
    
    BasicInformationViewController *a_gjCtr=[[BasicInformationViewController alloc]init];
    a_gjCtr.prModel = self.currentRecordModel;
    a_gjCtr.addressInfo = self.addressInfo;
    a_gjCtr.endTime = self.endTime;
    a_gjCtr.beginTime = self.beginTime;
    [controlArray addObject:a_gjCtr];
    
    // 附件信息
    GLDBViewController_Detail_B *Detail_B=[[GLDBViewController_Detail_B alloc]init];
    Detail_B.processRecoedArray = self.processRecoedArray;
    if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE&&self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK) {
        Detail_B.isEdit = NO;
    }else{
        Detail_B.isEdit = self.isEdit;
    }
    if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE) {
        Detail_B.duban = YES;
    }else if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW ){
        Detail_B.genjin = YES;
    }
    //添加跟进
    [controlArray addObject:Detail_B];
    
    // 流转信息
    JLLiuZhuanViewController *Detail_C=[[JLLiuZhuanViewController alloc]init];
    Detail_C.processRecordArray = self.processRecoedArray;
    //添加跟进
    [controlArray addObject:Detail_C];
    //设置选中字体颜色
    vc.titleSelectedColor = [TTTheme defaultManger].defaultColor;
    vc.buttonWidth = DEF_SCREEN_WIDTH/3;
    //添加标题
    vc.titleArray = @[@"基本资料", @"附件信息", @"流转信息"];
    //设置子视图
    vc.subViewControllers = controlArray;
    
    //标签栏背景色
    vc.headViewBackgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    //非选中状态下标签字体大小
    vc.fontSize=14.;
    //选中下划线颜色
    vc.bottomLineColor=[TTTheme defaultManger].defaultColor;
    
    vc.buttonHeight = 40.;
    [vc initSegment];
    [vc addParentController:self];
}

- (void)createView {
    UIButton *btn_1=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
    btn_1.backgroundColor=[UIColor whiteColor];
    [btn_1 setTitle:@"合格" forState:UIControlStateNormal];
    btn_1.layer.cornerRadius=3.;
    btn_1.tag=100;
    btn_1.titleLabel.font=[UIFont systemFontOfSize:11.];
    [btn_1 setTitleColor:[UIColor colorWithRed:0.29 green:0.68 blue:0.64 alpha:1.00] forState:UIControlStateNormal];
    [btn_1 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn_2=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
    btn_2.tag=101;
    btn_2.backgroundColor=[UIColor whiteColor];
    btn_2.titleLabel.font=[UIFont systemFontOfSize:11.];
    btn_2.layer.cornerRadius=3.;
    [btn_2 setTitle:@"不合格" forState:UIControlStateNormal];
    [btn_2 setTitleColor:[UIColor colorWithRed:0.75 green:0.19 blue:0.23 alpha:1.00] forState:UIControlStateNormal];
    [btn_2 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *bar_Btn_1=[[UIBarButtonItem alloc]initWithCustomView:btn_1];
    UIBarButtonItem *bar_Btn_2=[[UIBarButtonItem alloc]initWithCustomView:btn_2];
    self.navigationItem.rightBarButtonItems=@[bar_Btn_2,bar_Btn_1];
}

#pragma mark -methlod
- (void)clickAction:(UIButton *)sender{
    if (sender.tag==100) {
        // 合格
        _qualified = PROCESS_STAGE_CHECK_PASS_YES;
        [self showAlert];
        
    }else if(sender.tag==101){
        // 如果施工方整改后状态为待复查,复查不合格，状态是应该待复查还是待执行？
        //督办为无 仍为待复查
        if(self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK&&self.currentRecordModel.SEND_TYPE==4&&self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE){
            _qualified = PROCESS_STAGE_CHECK;
        }else{
            _qualified = PROCESS_STAGE_DOING;
        }
        [self showAlert];
        
    } else if (sender.tag==102) {
        
        if (self.content && ![self.content isEqualToString:@""]) {
            if (self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK&&self.currentRecordModel.SEND_TYPE==4&&self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateAttachment" object:nil];
            } else {
                [self reView:nil];
            }
            [alert hide];
            
        } else {
            [LSUtility showToastWithMessage:@"请输入说明" inView:self.navigationController.view Andtime:1.];
        }
    } else {
        //关闭复查
        [alert hide];
    }
}

- (void)showAlert {
    
    alert = [[FDAlertView alloc] init];
    AlertVIew *contentView=[[AlertVIew alloc]initWithFrame:CGRECTS(0, 0, 300, 200)];
    contentView.textViewBlock=^(NSString *value){
        self.content = value;
    };
    
    
    contentView.title.text = @"意见";
    
    //提交btn
    UIButton *submitBtn= contentView.submit;
    submitBtn.tag=102;
    [submitBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //关闭btn
    UIButton *closeBtn= contentView.closeBtn;
    closeBtn.tag=103;
    [closeBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //添加到alert
    alert.contentView = contentView;
    [alert show:self.view];
}

#pragma mark- 复查
- (void)reView:(NSNotification *)text {
    
    if (text) {
        NSDictionary *imageDic = text.userInfo;
        // 流程记录ID
        self.flowRecordID = imageDic[@"ID"];
        // 附件信息
        self.fileinfos = imageDic[@"ARRAY"];
        
    } else {
        // 流程记录ID
        self.flowRecordID = [NSUUID UUID].UUIDString;
        // 附件信息
        self.fileinfos = self.currentRecordModel.FILEINFOS;
    }
    
    // 修改流程
    [self zongJDuBanChangeFlow];
    // 添加流程记录
    [self addFlowRecordData];
    
    // 刷新监理督办列表
    [[NSNotificationCenter defaultCenter] postNotificationName:@"jianLiDuBan" object:nil];
    
    // 通知首页刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)zongJDuBanChangeFlow {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 修改流程
    NSString *sqlStr2 = [NSString stringWithFormat:@"UPDATE PROCESS SET END_TIME = '%@', PROCESS_STAGE = '%i', LOCAL_MODIFY_STATE = 'MOD', RECIFY_REVIEW_USERS = '%@',  MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'", [LSUtility nowTime], _qualified, USERID, DEF_PERSISTENT_GET_OBJECT(@"userid"), [LSUtility getIPAddress], [LSUtility nowTime], self.processId];
    
    if([db executeUpdate:sqlStr2]){
        NSLog(@"修改成功");
    }else{
        NSLog(@"修改失败");
    }
    [db close];
}


#pragma mark - 新增数据(流程记录表)
- (void)addFlowRecordData {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    DBHelper *dbhelper=[DBHelper help];
    
    // 复查意见
    NSString *explainStr = DEFISNUL(self.currentRecordModel.PROCESS_DESC);
    // 说明
    NSString *opinionStr = self.content;
    // 审阅人
    NSString *reviewUser = USERID;
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":DEFISNUL(self.flowRecordID),
                 @"PRO_ID":DEFISNUL(self.currentRecordModel.PRO_ID),
                 @"PROCESS_ID":DEFISNUL(self.processId),
                 @"WEATHER":DEFISNUL(self.currentRecordModel.WEATHER),
                 @"ADDRESS_ID":DEFISNUL(self.currentRecordModel.ADDRESS_ID),
                 @"ADDRES_INFO":DEFISNUL(self.currentRecordModel.ADDRES_INFO),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%ld", (long)self.currentRecordModel.PROCESS_TYPE],
                 @"PROCESS_STAGE":[NSString stringWithFormat:@"%d", _qualified],
                 @"RECORD_USER":USERID,
                 @"PROBLEM_TYPE":[NSString stringWithFormat:@"%ld", (long)self.currentRecordModel.PROBLEM_TYPE],
                 @"RECORD_MASTER":DEFISNUL(self.currentRecordModel.RECORD_MASTER),
                 @"RECIFY_USER":DEFISNUL(self.currentRecordModel.RECIFY_USER),
                 @"RECIFY_UNIT":DEFISNUL(self.currentRecordModel.RECIFY_UNIT),
                 @"SEVERITY":DEFISNUL(self.currentRecordModel.SEVERITY),
                 @"END_TIME":DEFISNUL(self.currentRecordModel.END_TIME),
                 @"SEND_TIME":DEFISNUL(self.currentRecordModel.SEND_TIME),
                 @"SEND_TYPE":[NSString stringWithFormat:@"%ld", (long)self.currentRecordModel.SEND_TYPE],
                 @"PROCESS_TITLE":DEFISNUL(self.currentRecordModel.PROCESS_TITLE),
                 @"PROCESS_CONTENT":DEFISNUL(self.currentRecordModel.PROCESS_CONTENT),
                 @"PROCESS_REQUIRED":DEFISNUL(self.currentRecordModel.PROCESS_REQUIRED),
                 @"PROCESS_DESC":DEFISNUL(explainStr),
                 @"SUBMITTORS":DEFISNUL(self.currentRecordModel.SUBMITTORS),
                 @"PUT_USER":DEFISNUL(self.currentRecordModel.PUT_USER),
                 @"REVIEW_USER":DEFISNUL(reviewUser),
                 @"REVIEW_OPINION":DEFISNUL(opinionStr),
                 @"REVIEW_STATE":[NSString stringWithFormat:@"%ld", (long)self.currentRecordModel.REVIEW_STATE ],
                 @"FILEINFOS":DEFISNUL(self.fileinfos),
                 @"EXTEND_INFO":DEFISNUL(self.currentRecordModel.EXTEND_INFO),
                 @"CREATE_USER_NAME":USERID,
                 @"CREATE_TIME":[LSUtility nowTime],
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":USERID,
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"MODIFY_TIME":[LSUtility nowTime],
                 @"LOCAL_MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"LOCAL_MODIFY_TIME":[LSUtility nowTime],
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    if (!pragameDic) {
        return;
    }
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS_RECORD];
    if(isAdd){
//        NSLog(@"验收记录新增成功");
    }else{
        NSLog(@"验收记录新增失败");
    }
    [db close];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

